﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Outdoors.Helpers.Flickr
{
    public class FlickrImage
    {
        public Uri Image320 { get; set; }
        public Uri Image1024 { get; set; }

        public async static Task<List<FlickrImage>> GetFlickrPhotos(double latitude = double.NaN, double longitude = double.NaN)
        {
            var flickrImages = new List<FlickrImage>();

            HttpClient client = new HttpClient();
            string flickrPhotosSearchUrl = FlickrAPI.PhotosSearchUrl(new GeoCoordinate(latitude, longitude));
            string flickrResult = await client.GetStringAsync(flickrPhotosSearchUrl);
            FlickrData flickrData = JsonConvert.DeserializeObject<FlickrData>(flickrResult);            

            if (flickrData.Stat == "ok")
            {
                foreach (var photo in flickrData.Photos.Photo)
                {
                    string photoUrl = "https://farm{0}.staticflickr.com/{1}/{2}_{3}";
                    string baseFlickrUrl = string.Format(photoUrl,
                        photo.Farm,
                        photo.Server,
                        photo.Id,
                        photo.Secret);

                    var flickrImage = new FlickrImage()
                    {
                        Image1024 = new Uri(baseFlickrUrl + "_b.jpg"),
                        Image320 = new Uri(baseFlickrUrl + "_n.jpg")
                    };

                    flickrImages.Add(flickrImage);
                }
            }

            return flickrImages;
        }
    }
}
